package LeetCode.interview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import LeetCode.interview._104_Maximum_Depth_of_Binary_Tree.TreeNode;
import sun.tools.jar.resources.jar;
import util.LogUtils;
import util.datastructure.ListNode;

/*
 * 
原题　
		Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
	
	You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
	
	Example:
	Given 1->2->3->4->5->NULL,
	return 1->3->5->2->4->NULL.
	
	Note:
	The relative order inside both the even and odd groups should remain as it was in the input.
	The first node is considered odd, the second node even and so on ...
	
	Credits:
	Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
	
题目大意
	
	给定一个单链表，将所有奇数节点组合在一起，然后是偶数节点。 请注意，我们正在谈论节点号而不是节点中的值。
解题思路
	
 * @Date 2017-10-06 00：04
 */
public class _328_Odd_Even_Linked_List {
	/**
	 * 法一：
	 * 	这里就是利用奇数和偶数位之间相互错位的位置关系。
	 * 		eg：
	 * 			1(奇数)节点的下一个节点：就是2(偶数)的下一个节点：3
	 * 			2(偶数)节点的下一个节点：就是3(奇数)的下一个节点：4
	 * 			....省略
	 * @param head
	 * @return
	 */
    public ListNode oddEvenList(ListNode head) {
    	if (head == null)	return null;
    	//头结点是奇数 
    	
    	ListNode pOdd     = head, pEvent     = head.next;
    	ListNode pOddHead = pOdd, pEventHead = pEvent;
    	while (pOdd!=null && pEvent!=null) {
    		if (pEvent == null)	break;
    		//
    		pOdd.next = pEvent.next;
    		pOdd = pOdd.next;
    		//
    		if (pOdd == null)	break;
    		pEvent.next = pOdd.next;
    		pEvent = pEvent.next;
    	}
    	//根据题意：偶链表接在奇链表之后 
    	pOdd = pOddHead;
    	while (pOdd.next != null)	pOdd = pOdd.next;		//找到奇链表尾结点
    	pOdd.next = pEventHead;
    	return pOddHead;
    }
	public static void main(String[] args) {
		_328_Odd_Even_Linked_List obj = new _328_Odd_Even_Linked_List();

		obj.oddEvenList(null);
	}

}
